package cn.edu.sdjzu.xg.eagle.util;

import lombok.Setter;

import java.util.ArrayList;
import java.util.List;

/**
 * @author tg.si@188.com
 * @todo
 * @since 2025/3/26 14:20
 */
@Setter
public class Condition {
    public Condition() {}
    public Condition(String key, String operator, String value) {
        this.key = key;
        this.operator = operator;
        this.value = value;
    }

    public String getKey() {
        return key;
    }

    public String getOperator() {
        return operator;
    }

    public String getValue() {
        return value;
    }

    public String toString() {
        return key + " " + operator + " " + value;
    }

    // 字段名
    private String key;
    // 操作符
    private String operator;
    // 字段值
    private String value;

    public static String toWhereClause(List<Condition> conditionList) {
        if (conditionList == null || conditionList.isEmpty()) {
            return ""; // 无条件时返回空字符串
        }

        StringBuilder sb = new StringBuilder(" WHERE "); // 注意末尾空格
        List<String> conditions = new ArrayList<>();

        for (Condition c : conditionList) {
            String operator = c.getOperator().toUpperCase(); // 统一转为大写
            String value = c.getValue();

            // 处理 LIKE 通配符
            if ("LIKE".equals(operator)) {
                value = "%" + value + "%";
            }

            // 所有字符串值包裹单引号（简单示例，实际需根据数据类型判断）
            value = TxtHelper.getSingleQuoteMarked(value);

            // 构建条件片段（确保格式为 `key operator 'value'`）
            String condition = String.format(
                    "%s %s %s",
                    c.getKey(),
                    operator,
                    value
            );
            conditions.add(condition);
        }

        // 使用 String.join 安全拼接 AND
        sb.append(String.join(" AND ", conditions));
        return sb.toString();
    }
}